<?php

use Illuminate\Database\Eloquent\ModelNotFoundException;

class AdminBrandController extends AdminController {

	public function getIndex(){
		if(!Cache::has('taxonomy-brand-all-data')){
			$data = Taxonomy::whereType('brand')->whereNull('deleted_at')->orderBy('order', 'desc')->get();
			Cache::put('taxonomy-brand-all-data', $data, 30);
		}

		$data = Cache::get('taxonomy-brand-all-data');

		$this->layout->title = trans('brand.list');
		$this->layout->content = View::make('admin.taxonomy.index', array('data' => $data, 'type' => 'brand'));
	}

	public function getCreate(){
		$this->layout->title = trans('brand.create');
		$this->layout->content = View::make('admin.taxonomy.form', array('type' => 'brand'));
	}

	public function getEdit($id){
		$this->layout->title = trans('brand.edit');

		try{
			$model = new Taxonomy;
			$data = $model->findOrFail($id);

			$this->layout->content = View::make('admin.taxonomy.form', array('taxonomy' => $data, 'type' => 'brand'));
		}catch(ModelNotFoundException $e){
			App::abort(404);
		}
	}

	public function postSave(){
		$this->layout = null;

		$data = Input::all();

		$model = new Taxonomy;

		$validator = $model->validator($data);

		if($validator->fails()){
			if(isset($data['id']) && $data['id'] > 0){
				$url = 'admin/brand/edit/' . $data['id'];
			}else{
				$url = 'admin/brand/create/';
			}

			return Redirect::to($url)->with('errors', $model->getErrorMessages())->withInput();
		}else{
			$model->saveData($data);
			return Redirect::to('admin/brand/');
		}
	}

	public function getDelete($id){
		$this->layout = null;

		try{
			$model = new Taxonomy;
			$data = $model->findOrFail($id);
			$data->delete();
			Cache::pull('taxonomy-brand-all-data');
			
			return Redirect::to('admin/brand/')->with('message', trans('brand.deleted'));
		}catch(ModelNotFoundException $e){
			App::abort(404);
		}
	}
}
